var App = getApp();
var ApiUrl = App.data.ApiUrl;
var Common = require('../../../utils/common.js');
Page({
  data: {
    token: '',
    orderno: '',
    paymoney: 0,
    code: '',
    canclick: true,
    selectIndex: 0,
    selectPay: {},
    showOther: true,
    payType: [],
    showMember: false,
    member: {},
    backScan: '',
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    var price = options.paymoney ? options.paymoney : page.data.paymoney;
    price = price - 1 + 1;
    this.setData({
      token: Common.get_token(),
      orderno: options.orderno ? options.orderno : page.data.orderno,
      paymoney: price.toFixed(2),
      itemId: options.itemId ? options.itemId : '',
      orders_id: options.orders_id,
      backScan: options.backScanCode ? options.backScanCode : '',
    });

    wx.setNavigationBarTitle({
      title: '支付'
    })

    this.getPayType();

    //this.getLoginCode();
    // this.checkSession();
    // this.authorize();
  },
  onShow(){
    getApp().getSaleMode()
  },
  getPayType() {
    var page = this;
    Common.my_request({
      url: '/AppMaster/pay/payWayAll',
      data: {
        orderno: page.data.orderno
      },
      success: (res) => {
        if (res.data.result == 0) {
          var data = res.data.data;
          if (data.length === 1 && data[0].pay_sign === 'other_pay') {
            const pay = data[0]
            const payobj = pay.methods.length > 0 ? pay.methods[0] : []
            this.setData({
              showOther: false,
              selectPay: payobj
            })
          }
          page.setData({
            payType: data
          })
        }
      }
    })
  },
  // 登录凭证
  getLoginCode: function () {
    wx.login({
      success: function (loginres) {
        if (loginres.code) {
          wx.setStorageSync("code", loginres.code)
        } else {
          console.log('获取用户登录态失败！' + loginres.errMsg)
        }
      }
    })
  },
  // 检测当前用户登录态是否有效
  checkSession: function () {
    wx.checkSession({
      success: function () {
        //session 未过期，并且在本生命周期一直有效
      },
      fail: function () {
        //登录态过期
        wx.redirectTo({
          // url: '/pages/login/login'
          url:'/pages/my/logintype/logintype'
        }); //重新登录
      }
    });
  },
  // 授权
  authorize: function () {
    var userinfo = wx.getUserInfo();
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
    wx.getSetting({
      success(res) {
        console.log(res);
        if (!userinfo) {
          wx.authorize({
            scope: userinfo,
            success(res) {
              console.log(res);
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              // wx.startRecord()
              // wx.getUserInfo();
            }
          })
        }
      }
    })
  },
  paytype(e) {
    var name = e.currentTarget.id,
      page = this,
      canclick = page.data.canclick;
    if (canclick) {
      if (name == "weChat_pay") {
        page.weixinPay();
      } else if (name == "other_pay") {
        page.otherPay();
      } else if (name == "balance_pay") {
        page.balancePay();
      }
    }
    page.setData({
      canclick: false
    })
  },
  balancePay() {
    var page = this;
    wx.showLoading({
      title: '请稍候',
      mask: true
    })
    Common.my_request({
      url: '/AppMaster/pay/balancePay',
      data: {
        order_no: page.data.orderno,
        orders_id: page.data.orders_id,
        total_money: page.data.paymoney
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.result == 0) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                if (page.data.backScan) { //扫码购跳回
                  // page.returnPre()
                  wx.redirectTo({
                    url: '/pages/order/index/index?fromMy=0'
                  })
                }
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                return false;
              }
            }
          })
        }
        page.setData({
          canclick: true
        })
      }
    })
  },
  weixinPay: function () {
    const {
      orders_id,
      orderno,
      itemId,
      paymoney,
      backScan
    } = this.data
    Common.weixinPay(orderno, paymoney, flag => {
      if (flag) {
        this.queryLevel()
        wx.navigateTo({
          url: `/subPage/paySuc/index?orderId=${orders_id}&money=${paymoney}`,
        })
      } else {
        if (itemId) {
          wx.redirectTo({
            url: '/pages/order/orderDetail/orderDetail?itemId=' + itemId
          })
        } else if (backScan) { //扫码购跳回
          wx.redirectTo({
            url: '/pages/order/index/index?fromMy=0'
          })
        } else {
          wx.navigateBack();
        }
      }
      this.setData({
        canclick: true
      })
    })
  },
  otherPay() {
    var page = this,
      orderno = this.data.orderno
    Common.my_request({
      url: '/AppMaster/pay/miniPayOther',
      data: {
        order_no: orderno
      },
      success: function (res) {
        wx.showModal({
          title: '提示',
          content: '订单已提交，等待顾问确认收款',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/order/index/index?fromMy=0'
              })
              page.setData({
                canclick: true
              })
            }
          }
        })
      }
    })
  },
  // 返回上一页
  returnPre: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },
  selectOther(e) {
    const {
      orderno,
      orders_id
    } = this.data
    const {
      id
    } = e.currentTarget
    if (id === 'pay_voucher') { //截图支付
      wx.navigateTo({
        url: `/subPage/payVoucher/index?order=${orderno}&orderId=${orders_id}`,
      })
      return
    }
    const {
      len
    } = e.currentTarget.dataset
    if (!len) {
      this.paytype(e)
      return
    }
    let {
      showOther,
      selectPay,
      payType
    } = this.data
    this.setData({
      showOther: !showOther
    })
    const {
      index
    } = e.currentTarget.dataset
    const pay = payType[index]
    const {
      methods
    } = pay
    if (!selectPay.name && methods) {
      selectPay = methods[0]
    }
    this.setData({
      selectPay
    })
  },
  selectPay(e) {
    let {
      payType,
      selectPay
    } = this.data
    const {
      index,
      pinx
    } = e.currentTarget.dataset
    const pay = payType[pinx]
    const {
      methods
    } = pay
    selectPay = methods[index]
    this.setData({
      selectIndex: index,
      selectPay
    })
  },
  save() {
    const {
      selectPay
    } = this.data
    const {
      url,
      bank_account_no
    } = selectPay
    if (url) {
      wx.downloadFile({
        url: url,
        success: res => {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: res => {
              wx.showToast({
                title: '已保存到相册',
                icon: 'none'
              })
              // console.log(this.data.backScan)
              // if (this.data.backScan) {  //扫码购跳回
              //   this.returnPre()
              // }
            },
            fail: error => {
              console.log(error)
            }
          })
        }
      })
    } else {
      wx.setClipboardData({
        data: bank_account_no,
      })
    }
  },
  onShareAppMessage(ops) {
    const {
      from
    } = ops
    if (from === 'button') {
      const {
        selectPay
      } = this.data
      return {
        title: '测试',
        imageUrl: selectPay.url
      }
    }
  },
  queryLevel() {
    Common.my_request({
      url: '/AppMaster/Notice/getNoticeList',
      data: {
        scene: 'order_pay_completion'
      },
      success: res => {
        const {
          data
        } = res.data
        if (data.length > 0) {
          const {
            new_lv
          } = data[0]
          this.setData({
            showMember: true,
            member: {
              level: new_lv
            }
          })
        }
      }
    })
  }
})